
#if !defined(AFX_CWADEVICE_H__2012__INCLUDED_)
#define AFX_CWADEVICE_H__2012__INCLUDED_

#include "../Inc/bt_ui.h"
#include "SerialPort.h"


#define				WA_PAIR_PIN_CODE		"1234"
#define				TO_COM_BUF_LEN			256
#define				FROM_COM_BUF_LEN		4096

class CWADevice
{
public:
	CWADevice(BLUETOOTH_DEVICE_INFO_EX* pDevInfoEx);
	~CWADevice();

	BOOL				InitDev();
	BOOL				UninitDev();

	DWORD				GetCommVersion(){return m_dwCommVersion;}
	CString				GetAddress();
	BOOL				GetAddress(BYTE* pAddres);
	CString				GetName();
	CString				GetDevID(){return m_szDevID;}
	void				SetDevID(CString strDevID){_tcscpy(m_szDevID, strDevID);}
	void				SetCommVersion(DWORD dwCommVersion){m_dwCommVersion = dwCommVersion;}

	BOOL				IsConnectedWA(){return m_bWAConnected;}
	void				SetConnectedWA(BOOL bConnected){m_bWAConnected = bConnected;}
	BOOL				IsDisconnBeforeConn(){return m_bDisconnBeforeConn;}
	void				SetBlueToothConnect(BOOL bConnect){m_DevInfoEx.bConnected = bConnect;}
	BOOL				IsBlueToothConnect(){return m_DevInfoEx.bConnected;}

	void				SetReadingGaitStart(BOOL bStart){m_bReadGaitStarted = bStart;}
	BOOL				IsReadingGaitStart(){return m_bReadGaitStarted;}

	BOOL				ExecuteCmd(BYTE* pInParam, int nInParamLen, BYTE* pOutResult, int nOutResultLen, int nTimeOut);
	BOOL				ClearBufFromCOM();

	DWORD				EventCallbackCOM(DWORD dwEvent);
	DWORD				AppendCOMByte(BYTE byteData);

	void				SetMRNCode(DWORD dwMRNCode){m_dwMRNCode = dwMRNCode;}
	DWORD				GetMRNCode(){return m_dwMRNCode;}

	DWORD				GetLastWAError(){return m_dwLastError;}

private:
	static UINT	WINAPI	WAWorkThread(LPVOID lpParam);

 	DWORD 				PairWADev();
	DWORD				UnpairWADev();
 	DWORD				ConnectSPPService();
	BOOL				DisconnectSPPService();
	DWORD				OpenCOMPort();

	BOOL				StartIO();
	BOOL				WriteCOM(OVERLAPPED* pOverlap);
	BOOL				ReadCOM(OVERLAPPED* pOverlap);

	void				PostProgressMsg(DWORD dwStrID, DWORD dwShowDuration);


private:
	HANDLE						m_hIOThread;

	BLUETOOTH_DEVICE_INFO_EX	m_DevInfoEx;			//  Contains 48-bit address
	GENERAL_SERVICE_INFO		m_SPPSvcInfo;			//  Service id and name
	
	DWORD						m_dwCOMPortNum;
	DWORD						m_dwSPPConnHandle;

	HANDLE						m_hCOMPort;

	BYTE						m_pDataToCOM[TO_COM_BUF_LEN];
	DWORD						m_dwDataLenToCOM;
	HANDLE						m_hToCOMDataReady;
	HANDLE						m_hToCOMDataEmpty;

	BYTE						m_pDataFromCOM[FROM_COM_BUF_LEN];
	DWORD						m_dwCurrentDataLenFromCOM;							

	DWORD						m_dwDataLenFromCOM;
	HANDLE						m_hFromCOMDataReady;
	HANDLE						m_hFromCOMDataEmtpy;

	DWORD						m_dwCommVersion;
	BOOL						m_bWAConnected;
	BOOL						m_bDisconnBeforeConn;
	BOOL						m_bReadGaitStarted;
	DWORD						m_dwMRNCode;

	volatile int				m_nWaitTimeBeforeRead;

	CSerialPort					m_Port;
	CRITICAL_SECTION			m_csDataFromCOM;

	DWORD						m_dwLastError;

	TCHAR						m_szDevID[50];
};

#endif//AFX_CWADEVICE_H__2012__INCLUDED_